<?php

ini_set('display_errors', 1);
ini_set('memory_limit', -1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';


/*
 * 修复后要查看order_goods这里是否有小于0的数据
 */

use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\model\trade\OrderRefund as mOrderRefund;


$refundList = mOrderRefund::select('*', [
    'status' => [mOrderRefund::STATUS_COMPLETE, mOrderRefund::STATUS_REFUNDING, mOrderRefund::STATUS_NORMAL, mOrderRefund::STATUS_WAIT_REFUND_GOODS, mOrderRefund::STATUS_WAIT_CONFIRM_RECEIPT, mOrderRefund::STATUS_REJECT],
]);


if (empty($refundList)) {
    die("无数据\n");
}


$refundLogData = [];
$refundOrder = [];

foreach ($refundList as $refundInfo) {
    $refundOrderGoods = ['refund_status' => mOrderGoods::REFUND_STATUS_CAN_NOT_REFUND];
    if (in_array($refundInfo['status'], [mOrderRefund::STATUS_NORMAL, mOrderRefund::STATUS_WAIT_REFUND_GOODS, mOrderRefund::STATUS_WAIT_CONFIRM_RECEIPT, mOrderRefund::STATUS_REJECT])) {
        @$refundOrderGoods = ['refund_amount' => $refundInfo['refund_rmb']];

        @$refundOrder[$refundInfo['order_no']]['refund_amount'] += ($refundInfo['refund_rmb'] + $refundInfo['refund_shipping_amount']);

    } elseif (in_array($refundInfo['status'], [mOrderRefund::STATUS_COMPLETE, mOrderRefund::STATUS_REFUNDING])) {
        @$refundOrderGoods = ['refunded_amount' => $refundInfo['refund_rmb']];

        @$refundOrder[$refundInfo['order_no']]['refunded_amount'] += ($refundInfo['refund_rmb'] + $refundInfo['refund_shipping_amount']);
        @$refundOrder[$refundInfo['order_no']]['refunded_shipping_amount'] += $refundInfo['refund_shipping_amount'];

    }

    //更新order_goods有退款的数据
    if (!empty($refundOrderGoods)) {
        mOrderGoods::update($refundOrderGoods, ['order_no' => $refundInfo['order_no'], 'sku_id' => $refundInfo['sku_id']]);
    }

}


$refundOrder = array_map(function ($v) {
    if (isset($v['refund_amount']) && $v['refund_amount'] <= 0) {
        $v['refund_amount'] = 0;
    }

    if(!isset($v['refund_amount'])){
        $v['refund_amount'] = $v['refunded_amount'];
    }

    $v['refunding_status'] = mOrder::REFUNDING_STATUS_PROCESS;

    return $v;
}, $refundOrder);


//更新order有退款的数据
foreach ($refundOrder as $orderNo => $refund) {
    mOrder::update($refund,['order_no'=>$orderNo]);
}


//更新历史脏数据
$excludeOrder = mOrderRefund::select(['order_no', 'sku_id'], ['order_no[!]' => array_keys($refundOrder)]);
foreach ($excludeOrder as $info) {

    mOrderGoods::update(['refund_amount' => 0, 'refunded_amount' => 0], ['order_no' => $info['order_no']]);

    mOrder::update(['refund_amount' => 0, 'refunded_amount' => 0, 'refunded_shipping_amount' => 0], ['order_no' => $info['order_no']]);

}
